package org.steven.crm.core.service.system;

import org.steven.crm.core.service.BaseService;
import org.steven.crm.core.utils.FileUtil;
import com.steven.common.utils.DateTimeUtil;
import com.steven.xdb.dbmanager.DBManager;
import com.steven.xdb.pagination.query.AbstractQueryDataList;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author wuzw
 * @Date 2024/1/4 17:51
 * @Version 1.0
 */
public class SystemFileService extends BaseService {
    private static SystemConfigService systemConfigService = new SystemConfigService();

    @Override
    protected String getTable() {
        return "systemFile";
    }

    @Override
    protected AbstractQueryDataList getQueryDataList() {
        return null;
    }

    @Override
    protected String getDataSourceName() {
        return null;
    }

    public Map<String, String> upload(File file, String originalName) throws Exception {
        FileUtil.FileMeta fileMeta = FileUtil.getFileMeta(file);
        Map<String, String> data = readByHash(fileMeta.getHash());
        if (!data.isEmpty()) {
            return data;
        }

        String baseDir = systemConfigService.getValue("uploadDir");
        String fileName = file.getName();
        String subUploadDir = DateTimeUtil.getCurrentDate();
        String dir = baseDir + File.separator + subUploadDir + File.separator;
        if (!new File(dir).exists()) {
            new File(dir).mkdirs();
        }
        cn.hutool.core.io.FileUtil.move(file, new File(dir + file.getName()), true);
        String path = subUploadDir + "/" + fileName;

        data.put("originalName", StringUtils.isEmpty(originalName) ? fileName : originalName);
        data.put("path", path);
        data.put("format", fileMeta.getMineType());
        data.put("size", fileMeta.getSize() + "");
        data.put("hash", fileMeta.getHash());
        data.put("duration", fileMeta.getDuration() + "");
        data.put("height", fileMeta.getHeight() + "");
        data.put("width", fileMeta.getWidth() + "");
        return this.create(data);
    }

    public Map<String, String> readByHash(String hash) throws Exception {
        Map<String, String> k = new HashMap<>();
        k.put("hash", hash);

        return DBManager.queryOne(getSession(), getTable(), k);
    }
}
